//
//  RegisterViewController.swift
//  ManBetX
//
//  Created by Cocoa on 2020/4/9.
//  Copyright © 2020 Fullen. All rights reserved.
//

import UIKit

class RegisterViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource{
    
    // MARK: -- property
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var eighteenYearsOldButton: UIButton!// 已满是18周岁
    @IBOutlet weak var registerButton: UIButton!// 注册
    
    // 验证码 ImageView
    var codeImageView: UIImageView = UIImageView.init()
    var viewLoginProgress:MBProgressHUD?
    lazy var dataArray:NSMutableArray = NSMutableArray.init()
    var sessionid :String = ""
    var dalegateIPA = false
    var needHiddenParams: [String] = []
    //mt  代理包传递的数据 代理码
    var agentCode: String?
    
    var accountString = ""// 账号
    var passwordString = ""// 密码
    var phoneNumberString = ""// 手机号
    var referralCodeString = ""// 推荐码
    var verifycodeString = ""// 验证码
    
    
    // MARK: -- cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.configureUI()
        self.configureDataSource()
        self.configureFromNet()
        self.updateVerificationCode()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //保证导航栏和页面push动画一致：上个页面设置的导航栏隐藏，需要在下个页面viewWillAppear时，开启导航栏展示
        // 设置导航栏显示
        self.navigationController?.setNavigationBarHidden(false, animated:true)
        addGradientLayer()
    }
    
    // MARK: -- func
    func configureUI() {
        self.title = "注册"
        
    }
    
    func addGradientLayer() {
        // 注意：需要控件创建frame布局后，渐变色layer才能加。否则会显示异常
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.registerButton.bounds
        gradientLayer.colors = [
            UIColor.init("FF914A")!.cgColor,
            UIColor.init("FBCE81")!.cgColor
        ]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        self.registerButton.layer.insertSublayer(gradientLayer, at: 0)
    }
    
    // 配置数据源
    func configureDataSource() {
        self.dataArray.removeAllObjects()
        let accountVM = RegisterViewModel.init(entity: RegisterViewModel.CaseType.account)
            accountVM.create()
        let passwordVM = RegisterViewModel.init(entity: RegisterViewModel.CaseType.password)
            passwordVM.create()
        let phoneNumberVM = RegisterViewModel.init(entity: RegisterViewModel.CaseType.phoneNumber)
            phoneNumberVM.create()
        let referralCodeVM = RegisterViewModel.init(entity: RegisterViewModel.CaseType.referralCode)
            referralCodeVM.create()
        let verificationCodeVM = RegisterViewModel.init(entity: RegisterViewModel.CaseType.verificationCode)
            verificationCodeVM.create()
        
        self.dataArray.add(accountVM)
        self.dataArray.add(passwordVM)
        self.dataArray.add(phoneNumberVM)
        self.dataArray.add(referralCodeVM)
        self.dataArray.add(verificationCodeVM)
        self.tableView.reloadData()
    }
    func configureFromNet(){
        if !dalegateIPA {
            self.updateRegParam()
        }
    }
    
    // 检测ViewMode是否全部输入正确 - 全部正确返回true
    func checkViewModelIsCorrect() -> Bool {
        
        for index in 0..<self.dataArray.count {
            let tempVM:RegisterViewModel = self.dataArray.object(at: index) as! RegisterViewModel
            // 不检查推荐码（非必填）
            if tempVM.caseType != .referralCode {
                      
               // 如果账号、密码、手机号有输入错误
               if tempVM.isErrorFlag {
                  return false
               }
               // 如果验证码没有输入
               if tempVM.caseType == .verificationCode,tempVM.textFieldString == ""{
                  UIHelper.alertSimpleMessage(about: "", withDescription: "请您输入验证码", in: self)
                  return false
               }
            }
        }
        return true
    }
    
    
    // MARK: -- tableView
    func getViewModel(index: Int) -> RegisterViewModel?{
        
        if index < self.dataArray.count {
            
            let tempVM = self.dataArray.object(at: index) as! RegisterViewModel
            return tempVM
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let tempVM = self.getViewModel(index: indexPath.row)

        return tempVM?.cellHeight() ?? 0.1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          
        return self.dataArray.count
          
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: RegisterTableViewCell.getIdentifier(), for: indexPath) as! RegisterTableViewCell
        let tempVM = self.getViewModel(index: indexPath.row)
        cell.configure(tempVM as Any)
        
        if tempVM?.caseType == .verificationCode {
            // 需要配置验证码
            self.codeImageView = cell.codeImageView
            cell.codeImageViewClickBlock = { [weak self] in
                
                self?.updateVerificationCode()
            }
        }
        if tempVM?.caseType == .account
            || tempVM?.caseType == .password
            || tempVM?.caseType == .phoneNumber {
            self.tableView.indexPath(for: cell)
                cell.errorFlagBlock = { [weak self] in
                    self?.reloadRow(indexPath:indexPath)
            }
        }
        return cell
    }
    
    func reloadRow(indexPath: IndexPath) {
        self.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.fade)
    }
    
    // MARK: -- @IBAction func
    // 注册按钮点击
    @IBAction func registertClick(_ sender: UIButton) {
        self.register()
    }
    
    // 我已满18周岁 - isSelected
    @IBAction func eighteenYearsOldButtonClick(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        print("eighteenYearsOldButtonClick")
    }
    
    // 协议点击
    @IBAction func protocolClick(_ sender: UIButton) {
        print("protocolClick")
    }
    
    // 更新验证码
    func updateVerificationCode(){
        NetWorkRequest(API.verifycode(url: "833656a"), completion: {(responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                 let dict =  responseData["data"].dictionaryValue
                 let imageStr =  dict["image"]?.stringValue
               
                let imageData = Data(base64Encoded: imageStr ?? "")
                self.codeImageView.image = UIImage(data: imageData ?? Data())
                self.sessionid = dict["sessionid"]?.stringValue ?? ""
                
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            self._loadView?.removeFromSuperview()
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
            }
        }) { () -> (Void) in
            self._loadView?.removeFromSuperview()
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "刷新验证码失败。", withDescription: "", in: self)
            }
        }
    }
    
    
    // 注册前的逻辑判断
    func register(){
        
        self.view.endEditing(true)
        
        if self.eighteenYearsOldButton.isSelected == false {
            MBProgressHUD.showMessage("未满18周岁!", to: view)
            return
        }
//        var requestParams: [String: String] = [
//            "wdpassword": "",
//            "gender": "0"
//        ]
        
        if self.checkViewModelIsCorrect() {
            for index in 0..<self.dataArray.count {
                let tempVM:RegisterViewModel = self.dataArray.object(at: index) as! RegisterViewModel
                if tempVM.caseType == .account{
                    self.accountString = tempVM.textFieldString
                }else if tempVM.caseType == .password{
                    self.passwordString = tempVM.textFieldString
                }else if tempVM.caseType == .phoneNumber{
                    self.phoneNumberString = tempVM.textFieldString
                }else if tempVM.caseType == .referralCode{
                    self.referralCodeString = tempVM.textFieldString
                }else if tempVM.caseType == .verificationCode{
                    self.verifycodeString = tempVM.textFieldString
                }
            }
            registerNext([
                "joiname": accountString,
                "pwd": passwordString,
                "uphone": phoneNumberString,
                "verifycode": verifycodeString
            ])
        }
    }
    // 注册调用网络之前的逻辑
    func registerNext(_ params: [String:String]) {
        var requestParams = params
        requestParams["birthyear"] = "0"
        requestParams["birthmonth"] = "0"
        requestParams["birthday"] = "0"
        requestParams["gender"] = "0"
        requestParams["checkbox"] = "1"
        requestParams["email"] = ""
        requestParams["fullname"] = ""
        requestParams["uid"] = ""
        requestParams["jsessionid"] = self.sessionid
        if dalegateIPA {
            requestParams["agc"] = "36774"    ///代理APP才有
        }else{
            if self.referralCodeString.count > 0 {
                if self.agentCode != nil{
                    requestParams["agc"] = self.agentCode
                }else{
                     requestParams["agc"] = self.referralCodeString
                }
            }else{
                requestParams["agc"] = "10000"
            }
        }
        requestParams["pwd"] = params["pwd"]
        let enPwd = self.decrypt(data: params["pwd"] ?? "" , n: 4)
        requestParams["joinpwd"] = enPwd
         actionRegister2(withParams: requestParams)
    }
    
    // 注册 - 请求服务器
    func actionRegister2(withParams params: [String:String]){
        self._loadView?.removeFromSuperview()
        self._loadView = UIHelper.initLoadView(self, offsetY: -64)
        self.view.addSubview(self._loadView!)
        weak var this = self
        NetWorkRequest(API.registerUser(url: "a9451c8", parameters: params), completion: { (responseData,statusCode,strData) -> (Void) in
            DispatchQueue.main.async {
                let dict =  responseData["data"].dictionaryValue
               let responseDict = dict["responseReg"]?.dictionaryValue
                let c = responseDict?["c"]?.intValue ?? -1
                let msg = responseDict?["m"]?.stringValue ?? ""
                self._loadView?.removeFromSuperview()
                switch c{
                case 0:
                    this?.viewLoginProgress = MBProgressHUD.showMessageNoHiden("注册成功，自动登录中", to: this!.view)
                    let defaults = UserDefaults.standard
                    let tokenDict = dict["resultCookies"]?.dictionaryObject
                    let ccToken =  tokenDict?["cc"] as? String ?? ""
                    let vcToken =  tokenDict?["vc"] as? String ?? ""
                    if(isTest){
                        defaults.set(vcToken, forKey: DefaultKey.VCTOKEN81)
                        defaults.set(ccToken, forKey: DefaultKey.CCTOKEN81)
                    }else{
                        defaults.set(vcToken, forKey: DefaultKey.VCTOKEN11)
                        defaults.set(ccToken, forKey: DefaultKey.CCTOKEN11)
                    }
                    RequestHelper.makeCFCookie()
                    RequestHelper.addTokenCookies()
                    RequestHelper.makeGameDomainCookie()
                    
                    defaults.set(false, forKey: DefaultKey.USER_IS_SAVE_PASSWORD)
                    defaults.set(params["joiname"], forKey: DefaultKey.USER_LOGIN_NAME)
                    defaults.set(nil, forKey: DefaultKey.USER_LOGIN_PASSWORD)
                    UserHelper.setLoginStatus(true)
                    self.performEnterMainPageRequest2True(withLogin: true, dict: dict)
                    this?.viewLoginProgress = MBProgressHUD.showMessageNoHiden("注册成功，自动登录中", to: this!.view)
                    
                    self.dismiss(animated: true, completion: nil)
                    break
                case 1101:
                    if msg.contains("joiname") {
                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的账号有误（4-11个字符, 仅可输入英文字母以及数字的组合），请重新输入。", in: self)
                        
                    }
                    if msg.contains("joinpwd") {
                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的密码有误（密码长度为6-16个字符,须含有字母和数字组合），请重新输入", in: self)
                        
                    }
                    if msg.contains("wdpassword") {
                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的取款密码有误密码长度为6-16个字符,须含有字母和数字组合），请重新输入", in: self)
                        
                    }
                    if msg.contains("fullname") {
                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的真实姓名有误，请您核对您的账号信息，账号关系到您的资金安全，请您核对后重新输入", in: self)
                        
                    }
                    if msg.contains("uphone") {
                        UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的手机号码格式有误，请您核对后重新输入", in: self)
                        
                    }
                    
                    self.updateVerificationCode()
                    break
                case 1103:
                    UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的账号已被使用（4-11个字符, 仅可输入英文字母以及数字的组合），请您重新输入", in: self)
                    self.updateVerificationCode()
                    break
                case 998:
                    UIHelper.alertSimpleMessage(about: "注册失败", withDescription: "您输入的验证码有误，请重新输入", in: self)
                    self.updateVerificationCode()
                    break
                default:
                    UIHelper.alertSimpleMessage(about: "注册失败", withDescription: CodeMessageHelper.get(String(c)), in: self)
                    self.updateVerificationCode()
                    break
                }
            }
        }, failed: { (faildInfo,reCode,msg) -> (Void) in
            self._loadView?.removeFromSuperview()
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                self.updateVerificationCode()
            }
        }) { () -> (Void) in
            self._loadView?.removeFromSuperview()
            DispatchQueue.main.async {
                UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
                self.updateVerificationCode()
            }
        }
    }
    
    //加密
    func decrypt(data:String,n:Int) ->String{
        var len:Int =  n
        let letters: String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        let letterLen:Int = letters.count/2
        if len == -1{
            len = letterLen/2
        }
        len=len%letterLen
        if len == 0{
            return data
        }
        if len < 0{
            len += letterLen
        }
        let str1 =  letters.suffix(letters.count-(len * 2))
         let startindex =  letters.index(letters.startIndex, offsetBy: 0)
        let endIndex =  letters.index(letters.startIndex, offsetBy: len * 2)
        let str2 = letters[startindex..<endIndex]
        let rep:String = String(str1 + str2)
       let data2 = self.replaceChars(str: data, searchChars: letters, replaceChar: rep)
        return data2
    }
    func checkCondition(text: String, withPattern: String) -> Bool {
        if let range = text.range(of: withPattern, options: .regularExpression){
            let subString = text.substring(with: range)
            return !text.isEmpty && subString == text
        }
        return false
    }
    
    //仿写Apache StringUtils工具类的replaceChars方法
    func replaceChars(str:String?,searchChars:String?,replaceChar:String?) -> String{
        let replaceChars :String = replaceChar ?? ""
        if str != nil && searchChars != nil {
            var modified :Bool = false
            let replaceCharsLength :Int = replaceChars.count
            let strLength:Int = str!.count
            var buf :String = ""
            for i in 0...strLength-1 {
                let startindex =  str!.index(str!.startIndex, offsetBy: i)
                let endIndex =  str!.index(str!.startIndex, offsetBy: i+1)
                let ch = str![startindex..<endIndex]
                print("ch--\(ch)")
                let temstr: NSString = searchChars! as NSString
            
                var index:Int  = temstr.range(of: String(ch)).location
                if(index == NSNotFound){
                    index = -1
                }
                print("index---\(index)")
                if index >= 0 {
                    modified = true
                    if index < replaceCharsLength {
                        let rstartindex =  replaceChars.index(replaceChars.startIndex, offsetBy: index)
                        let rendIndex =  replaceChars.index(replaceChars.startIndex, offsetBy: index+1)
                        let str4 = replaceChars[rstartindex..<rendIndex]
                        buf += str4
                    }
                }else{
                    buf += ch
                }
            }
            if modified == true{
                print("\(buf)")
                return buf
            } else {
                return str ?? ""
            }
        } else {
            return str ?? ""
        }
    }
    
    func updateRegParam(){
        RequestHelper.get(atPath: "/clientsAPIs/regParam", withCompletion: { data in
            let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]
            print("!!!!!\(dataArray)")
            for key in dataArray.keys {
                if key != "dcode" {
                    if dataArray[key] as? String ?? "" != "ON" {
                        self.needHiddenParams.append(key)
                    }
                }else if key == "dcode" {
                    if dataArray[key] as? Int != 10000 {
                        self.needHiddenParams.append(key)

                        self.agentCode=dataArray[key] as? String
                        DispatchQueue.main.async {
                           self.tableView .reloadData();
                        }
                    }
                }
            }
//            self.tableView.reloadData()
//            self.tableView.isUserInteractionEnabled = true
            self._loadView?.removeFromSuperview()

        }, withError: { error in
            DispatchQueue.main.async {

                let dialogMessage = UIAlertController(title: "无法获取注册信息，请联络客服。\(getErrorString())", message: "", preferredStyle: .alert)
                dialogMessage.view.tintColor = UIColor.black

                // Create OK button with action handler
                let ok = UIAlertAction(title: "知道了", style: .default, handler: { (action) -> Void in
                    DispatchQueue.main.async(execute: {
                        self.navigationController?.popViewController(animated: true)
                    })
                })

                //Add OK and Cancel button to dialog message
                dialogMessage.addAction(ok)

                // Present dialog message to user
                self.present(dialogMessage, animated: true, completion: nil)
            }
        })
    }
    
    func performEnterMainPageRequest2True(withLogin: Bool = false,dict: [String : JSON]){
        
        let maintainData: [String:String]? = nil
        let platforms = GlobalInfo.gameInfoData?["platforms"] as? [[String:Any]] ?? [[String:Any]]()
        if GlobalInfo.isMaintain() == true{
            if withLogin {
                DispatchQueue.main.async {
                    UIHelper.alertIsMainTain(about:"系统维护",withDescription:GlobalInfo.gameInfoData?["maintain_msg"] as! String,urlString:GlobalInfo.gameInfoData?["maintain_cs_url"] as! String)
                }
            }
            return
        }
        DispatchQueue.main.async {
         let responseDict = dict["resultGetGameStatus"]?.dictionaryValue
          let responseDataDict =  responseDict?["response"]?.dictionaryValue
          let hallArr = responseDataDict?["data"]?.arrayObject  as? [[String : Any]] ?? [[String : Any]]()
            let memberinfoDict = dict["resultGetMemberInfo"]?.dictionaryObject
            let resultGetInfoDict = dict["resultGetInfo"]?.dictionaryValue
            let resultGetInfoDataDict = resultGetInfoDict?["response"]?.dictionaryObject ?? [String : Any]()
            
            GlobalInfo.memberInfoData = memberinfoDict
            GlobalInfo.siteInfoData = resultGetInfoDataDict
            GlobalInfo.platformInfoData = platforms
            
            GlobalInfo.hallInfoData = hallArr
            GlobalInfo.gameMaintainData = maintainData
            
            //        openAdView()
        }
    }
    
}



